/* list_dir.c: fontman engine, for all POSIX compatible systems. */

#include "libfontman.h"
#include "internal.h"

extern fontman_list_t list_context;

int fontman_list_dir_init(const char *path)
{
    DIR *dirp;

    dirp = opendir(path);
    if (dirp == NULL)
        return FONTMAN_ERR_PATH_OPEN;

    list_context.u.dirp = dirp;
    return 0;
}

int fontman_list_dir_next(char *path, int max_len)
{
    struct dirent *dp;
    int len;

    dp = readdir(list_context.u.dirp);
    if (dp == NULL)
        return FONTMAN_ERR_NO_NEXT;

    if (fnmatch(FONTMAN_FILE_NAME_PATTERN, 
                dp->d_name, FNM_CASEFOLD) != 0)
        return fontman_list_dir_next(path, max_len);

    if (strlen(list_context.path) + 
        strlen(dp->d_name) + 1 >= max_len)
        return fontman_list_dir_next(path, max_len);

    strcpy(path, list_context.path);
    
    len = strlen(path);
    if (path[len - 1] != PATH_SEP)
    {
        path[len] = PATH_SEP;
        path[len + 1] = '\0';
    }

    strcat(path, dp->d_name);
    return 0;
}

void fontman_list_dir_free()
{
    closedir(list_context.u.dirp);
}

